package com.eppear.jpfm.framework.websocket.client;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSONObject;
import com.eppear.jpfm.framework.constants.Constants;
import com.eppear.jpfm.framework.model.WsMessage;
import com.eppear.jpfm.framework.util.SysUtil;
import com.eppear.jpfm.framework.websocket.WebSocketClientService;


/**
 * @ClassName ClientHandler
 * @Description
 *         WebSocket客户端处理器<br>
 *         
 *          微信客户端            微信服务器       应用服务器         前置服务器     <br>
 *                |             |            |               |      <br>   
 *   1.连接             |             |        校验 |<--------------|      <br>   
 *                |             |        成功 |-------------->|      <br>   
 *                                                                  <br>    
 *   2.微信请求 .  |------------>|------------>|-------------->|-┓    <br>  
 *                |<------------|<------------|<--------------|<┛    <br>  
 *                                                                  <br>   
 *   3.主动发送      |<------------|<------------|<--------------|     <br>   
 *        
 *        
 * @author JianFeng Zhang(张建锋)
 * @date   2017-09-28 上午8:08:36
 *
 */
public class ClientHandler extends TextWebSocketHandler {

	private static final Logger log = LoggerFactory.getLogger(ClientHandler.class);
	private static WebSocketSession ss; 
	@Autowired
	private WebSocketClientService wscs;
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		this.ss = session;
		super.afterConnectionEstablished(session);
		log.debug( "客户端 ===> 与服务器连接成功!" );
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		super.handleTextMessage(session, message);
		String reply = message.getPayload();
		log.info("客户端 <=== 收到服务器请求消息:[{}]",reply);
		//WxMessage<String> reqMessage = (WxMessage<String>)JSONObject.parseObject(reply);
		WsMessage<Map> reqMessage = SysUtil.jsonString2Obj(reply,WsMessage.class);
		WsMessage<?> resMessage = wscs.doResponse(reqMessage);
		if (resMessage != null && session.isOpen()) {
			String resMsg = JSONObject.toJSONString(resMessage);
			session.sendMessage(new TextMessage(resMsg));
			log.info("客户端 ===> 回复服务器请求消息为:[{}]",resMsg);
		}
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		super.handleTransportError(session, exception);
		log.error("客户端 ===> 通讯出错!{}",exception);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		super.afterConnectionClosed(session, status);
		if(session.isOpen()){
			session.close();
		}
		log.debug("客户端 ===> 和服务器断开 了连接!");
	}
	
	/**
	 * 主动发送文本消息到服务端
	 * @param message
	 * @return 0成功,其它失败
	 */
	public static Integer sendTextMessage(WsMessage message){
		if(ss !=null && ss.isOpen()){
			try {
				ss.sendMessage(new TextMessage(JSONObject.toJSONString(message)));					
			} catch (IOException e) {
				log.error("websocket发送信息失败!消息为:{}",JSONObject.toJSONString(message));
				return Constants.ERROR_CODE_00023;
			}
			log.info("客户端 ===> 发送消息到服务端:[{}]",JSONObject.toJSONString(message));
		}else{
			return Constants.ERROR_CODE_00021;			
		}
		return Constants.ERROR_CODE_00000;	
	}
	
	/**
	 * 是否连接成功
	 * @return
	 */
	public static Boolean isconnected() {
		return (ss !=null && ss.isOpen());
	}
    
}
